package hot;

import java.util.ArrayList;
import java.util.List;

/**
 * @author way
 * @create 2025-03-14 21:34
 */
public class _22_generateParenthesis {
    List<String> ans = new ArrayList<>();
    StringBuilder path = new StringBuilder();

    public List<String> generateParenthesis(int n) {
        dfs(n, 0, 0);
        return ans;
    }

    //  ( > n 或 ) > n 或 ) > (
    private void dfs(int n, int left, int right) {
        if (left > n || right > n || left < right) return;
        if (path.length() == 2 * n) {
            ans.add(path.toString());
            return;
        }

        path.append("(");
        dfs(n, left + 1, right);
        path.deleteCharAt(path.length() - 1);
        path.append(")");
        dfs(n, left, right + 1);
        path.deleteCharAt(path.length() - 1);


    }
}
